// What helps debugging :
// http://getfirebug.com/
// Once install, don't hesitate to use console.log(variable) in your javascript's scripts to see the content of any variable or server return in the Firebug console

var tmaticIdentityService=null;
var username=null;
var token=null;
var appId = "appId_4a8a4fc1d34714.12449913";
var server = "http://www.t-ma-tic.com";

//Called when the body loads

function initialize() {
	$('req').addEvent('keyup', onSearchKeyUp);
	$('addTmaticButton').addEvent('click', addTmaticToProfile);
	$('removeTmaticButton').addEvent('click', removeTmaticFromProfile);
	tmaticIdentityService = new TmaticIdentityService(appId, onLogin);
	getProfile();
}

//Events Handlers

function login() { //Called when "login" links is clicked
	$('tmatic_identity').setStyle('display' , 'block');
	if(typeof tmaticIdentityService == 'object')
	{
		tmaticIdentityService.getIdentity();
		//calls onLogin on successfull login
	}
}

function onLogin(u, t) { //call by default after authentication by tmaticIdentityService.getIdentity();
	username = u;
	token = t;
	$('log').innerHTML = "Connected as " + username;
	
	$('tmatic_identity').empty();
	$('tmatic_identity').setStyle('display' , 'none');
	
	if(token && username)
	{
		getProfile();
	}
}

function onSearchKeyUp() {
	var req = $('req').value;	
	getTmatics(req);
}

// Manages Add and Remove buttons

function clearRemoveTmaticButton()
{
	$('removeTmaticButton').empty();
	$('removeTmaticButton').tmatic = null;
	$('removeTmaticButton').semecode = null;	
}

function clearAddTmaticButton()
{
	$('addTmaticButton').empty();
	$('addTmaticButton').tmatic = null;
	$('addTmaticButton').semecode = null;
}

//JSONP requests to t-ma-tic.com API

function getTmatics(req, div) {
	
	var semecode = null;
	var tmatic = null;

	clearAddTmaticButton();
	clearRemoveTmaticButton();
	
	if(div)
	{
		semecode = div.semecode;
		tmatic = div.tmatic;
		
		if(username)
		{
			if(div.getParent() == $('profile'))
			{
				var label = new Element('div', {'html' : 'Remove ' + tmatic + ' from ' + username + "'s profile", 'class' : 'removeTmaticLabel'});
				label.inject($('removeTmaticButton'));
				$('removeTmaticButton').tmatic = tmatic;
				$('removeTmaticButton').semecode = semecode;				
			}
			else
			{
				var label = new Element('div', {'html' : 'Add ' + tmatic + ' to ' + username + "'s profile", 'class' : 'addTmaticLabel'});
				label.inject($('addTmaticButton'));
				$('addTmaticButton').tmatic = tmatic;
				$('addTmaticButton').semecode = semecode;
			}
		}
	}
	
	$('loading').setStyle('display', 'inline');
	var rememberMe = Cookie.read('rememberMe');

	new Request.JSONP({
	  url: server + '/factory/getP',
	    data: {
	        q: req,
	        s: semecode,
	        rememberMe: rememberMe
	    },
	    onComplete: function(tmatics) {
	    	getTmaticsHandler(tmatics)
	    }
	}).send();
}

function getProfile() {
	$('loading').setStyle('display', 'inline');
	var rememberMe = Cookie.read('rememberMe');
	
	new Request.JSONP({
	  url: server + '/factory/getProfileP',
	    data: {
	        t: token,
	        appId: appId,
	        rememberMe: rememberMe
	    },
	    onComplete: function(response) {
	    	getProfileHandler(response);
	    }
	}).send();
}

function addTmaticToProfile() {	
	var semecode = $('addTmaticButton').semecode;
	
	if(semecode == null)
	{
		return;
	}
	
	$('loading').setStyle('display', 'inline');
	var rememberMe = Cookie.read('rememberMe');
	
	new Request.JSONP({
	  url: server + '/factory/addP',
	    data: {
	        t: token,
	        appId: appId,
	        s: semecode,
	        rememberMe: rememberMe
	    },
	    onComplete: function(response) {
	    	addTmaticHandler(response);
	    }
	}).send();	
}

function removeTmaticFromProfile() {
	var semecode = $('removeTmaticButton').semecode;
	
	if(semecode == null)
	{
		return;
	}
	
	$('loading').setStyle('display', 'inline');
	var rememberMe = Cookie.read('rememberMe');
	
	new Request.JSONP({
	  url: server + '/factory/removeP',
	    data: {
	        t: token,
	        appId: appId,
	        s: semecode,
	        rememberMe: rememberMe
	    },
	    onComplete: function(response) {
	    	removeTmaticHandler(response);
	    }
	}).send();
}

//Handlers (Functions that handles results from JSONP requests)

function getTmaticsHandler(tmatics) {
	var div = new Element('div', {'class' : 'inner','styles' : {'padding' : '10px'}});

	for(y=0 ; y<tmatics['tmatics'].length; y++)
	{
		renderTmatic(tmatics['tmatics'][y]['title'], tmatics['tmatics'][y]['semecode'],'current' ).inject(div);
		
		if(tmatics['tmatics'][y]['similar']) 
		{
			for(var x=0 ; x< tmatics['tmatics'][y]['similar'].length; x++) 
			{
				renderTmatic(tmatics['tmatics'][y]['similar'][x]['title'], tmatics['tmatics'][y]['similar'][x]['semecode'], 'similar').inject(div);
			}
		}

		if(tmatics['tmatics'][y]['linked']) 
		{
			for(var x=0 ; x< tmatics['tmatics'][y]['linked'].length; x++) 
			{
				renderTmatic(tmatics['tmatics'][y]['linked'][x]['title'], tmatics['tmatics'][y]['linked'][x]['semecode'], 'linked').inject(div);
			}
		}
	}

	$('searchResults').innerHTML = '';	
	div.inject($('searchResults'));
	
	$('loading').setStyle('display', 'none');
}

function getProfileHandler(response) {
	
	if(response.username)
	{
		username = response.username;
	}
	
	var div = $('profile');
	
	div.empty();
	$('profileTitle').empty();
	
	div.empty();
	
	$('profileTitle').innerHTML = username + "'s profile";
	
	for(var i=0; i < response.profile.length; i++)
	{
		var tmatic = response.profile[i].title;
		var semecode = response.profile[i].semecode;
		var tmaticDiv = renderTmatic(tmatic, semecode, 'current');
		tmaticDiv.inject(div);
	}
	
	$('loading').setStyle('display', 'none');
}

function addTmaticHandler(response)
{
	getProfile();
	clearAddTmaticButton();
}

function removeTmaticHandler(response)
{
	getProfile();
	clearRemoveTmaticButton();
}

//Rendering functions (From JSON to HTML)

function renderTmatic(tmatic, semecode, c) {
	var el = new Element('div', {'class' : c, 'html' : tmatic, 'events' : {'click' : function(){ getTmatics('',this); } }}); 				
	el.tmatic = tmatic;
	el.semecode = semecode;
	
	return el;	
}

